package com.chaowei.lims.fragment;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TimeZone;

import org.ksoap2.serialization.SoapObject;

import com.chaowei.lims.R;
import com.chaowei.lims.activity.AllFuncsActivity;
import com.chaowei.lims.activity.BillActivity;
import com.chaowei.lims.activity.BillDetailActivity;
import com.chaowei.lims.activity.CustInfoActivity;
import com.chaowei.lims.activity.LabActivity;
import com.chaowei.lims.activity.LoginActivity;
import com.chaowei.lims.activity.MainActivity;
import com.chaowei.lims.activity.BillActivity.AsyncLoadBillListner;
import com.chaowei.lims.activity.NewCommissionActivity;
import com.chaowei.lims.activity.ReportActivity;
import com.chaowei.lims.activity.PaymentRecordActivity;
import com.chaowei.lims.adapter.BillAdapter;
import com.chaowei.lims.entity.WcfWrapper;
import com.chaowei.lims.utils.AsyncOptUIListener;
import com.chaowei.lims.utils.CcCircleImageView;
import com.chaowei.lims.utils.InitData;
import com.chaowei.lims.utils.MyApplication;
import com.chaowei.lims.utils.SoapRequest;
import com.chaowei.lims.utils.myComparator;
import com.chaowei.lims.utils.myGridview;
import com.chaowei.lims.utils.myListView;
import com.google.zxing.common.Collections;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.app.Activity;
import android.app.Fragment;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.ViewSwitcher;

public class HomepageFagment extends Fragment {
	private ImageView imgPopBack;
	private EditText etSearch, edSearchPop;
	private PopupWindow popSearch;
	private View contentView;
	private CcCircleImageView cciAccount;
	private ImageView imgPiture,imgPopsearch;
	private GridView gvEntrance, gvTodo,gvNotapproved;
	private PullToRefreshScrollView mPullRefreshScrollView;
	private SimpleAdapter entrAdapter, todoAdapter,notapproAdapter;
	private BillAdapter totalBillAdapter, searchBillAdapter;
	private ArrayList<HashMap<String, Object>> funcsList = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> todoList = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> notapproList = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> billMasterList = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> billSearchList = new ArrayList<HashMap<String, Object>>();
	private ArrayList<HashMap<String, Object>> billRecentList = new ArrayList<HashMap<String, Object>>();
	private TextSwitcher tsMsg;
	private Handler mHandler;
	private Thread myThread;
	private int msgIndex = 0;
	private Boolean isContinue;
	private ArrayList<String> msgInfoList = new ArrayList<String>();
	private MyApplication app;
	//private myListView listTotalBill;
	private ListView listSearchBill;
	private SharedPreferences image;
	private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
	private String login_id;
	private SoapObject cert;
	private WcfWrapper totalBillWrapper = new WcfWrapper();
	private WcfWrapper notApprovedBillWrapper = new WcfWrapper();
	private WcfWrapper detectionBillWrapper = new WcfWrapper();
	private WcfWrapper msgWrapper = new WcfWrapper();
	private String username, real_name;
	private TextView tvDetec, tvNotApprove;
	private LinearLayout linCircleHeader;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_homepage, container,
				false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		app = MyApplication.getInstance();
		cert = app.getPermanentCert();
		login_id = getActivity().getIntent().getExtras().getString("login_id");
		
		for(int i = 0;i<app.getDbFunsList().size();i++){
			funcsList.add(app.getDbFunsList().get(i));
		}
		initView();
		initTextSwitcher();
		LoadMessage();
		initData();
		bindData();
//		LoadTotalContracts();
//		LoadDetectionOfContracts();
//		LoadNotApprovedContracts();
		setListener();

		// 读取头像的图片
		image = getActivity().getSharedPreferences("ImageInfo",
				Context.MODE_PRIVATE);
		String imaePath = image.getString(username, null);
		if (image != null && imaePath != null) {
			Bitmap bm = BitmapFactory.decodeFile(imaePath);
			cciAccount.setImageBitmap(bm);

		}

	}

	@Override
	public void onStart() {
		super.onStart();
		entrAdapter.notifyDataSetChanged();
	}

	class ItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Intent intent = new Intent(getActivity(), BillActivity.class);
			switch (arg2) {
			case 0:
				app.setState(app.BILLSTATE_ALL);
				startActivity(intent);
				break;
			case 1:
				app.setState(app.BILLSTATE_NOT_APPROVED);
				startActivity(intent);
				break;
			case 2:
				app.setState(app.BILLSTATE_DETECTION);
				startActivity(intent);
				break;
			case 3:
				app.setState(app.BILLSTATE_FINISHED);
				startActivity(intent);
				break;
			case 4:
				Bundle bundle = new Bundle();
				bundle.putString("login_id", login_id);
				bundle.putString("username", username);
				bundle.putString("realName", real_name);
				Intent funcIntent = new Intent(getActivity(),
						NewCommissionActivity.class);
				funcIntent.putExtras(bundle);

				startActivity(funcIntent);
				break;
			case 6:
				Intent itent = new Intent(getActivity(),AllFuncsActivity.class);
				startActivity(itent);
				break;
			}

		}

	}

	/** 初始化布局控件 */
	private void initView() {

		mPullRefreshScrollView = (PullToRefreshScrollView) getActivity()
				.findViewById(R.id.PullToRefreshScrollView_home_refresh);
		cciAccount = (CcCircleImageView) getActivity().findViewById(
				R.id.cccircleImageView_header_account);
		etSearch = (EditText) getActivity().findViewById(R.id.sv_header_search);
		
		imgPiture = (ImageView) getActivity().findViewById(R.id.ib_header_scan);

		getActivity().getLayoutInflater();
		contentView = LayoutInflater.from(getActivity()).inflate(
				R.layout.popupwindow_search, null);
		imgPopsearch = (ImageView)contentView.findViewById(R.id.img_pop_search);
		popSearch = new PopupWindow(contentView,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		initSearchPopuWindow();
		imgPopBack = (ImageView) contentView
				.findViewById(R.id.img_searchpop_cancle);
		edSearchPop = (EditText) contentView
				.findViewById(R.id.ed_searchpop_search);

		listSearchBill = (ListView) contentView
				.findViewById(R.id.list_bill_popsearch);
		gvEntrance = (myGridview) getActivity().findViewById(
				R.id.gv_home_entrance);
		
		gvTodo = (myGridview) getActivity().findViewById(
				R.id.gv_home_todo);
		
		gvNotapproved = (myGridview) getActivity().findViewById(
				R.id.gv_home_notapproved);
		tsMsg = (TextSwitcher) getActivity().findViewById(R.id.ts_home_msg);
		username = getActivity().getIntent().getStringExtra("username");
		real_name = getActivity().getIntent().getStringExtra("realName");

		linCircleHeader = (LinearLayout)getActivity().findViewById(R.id.lin_cccircleImageView_header_account);

	}

	/**
	 * 设置TextSwitcher显示
	 */
	private void initTextSwitcher() {
		isContinue = true;
		tsMsg.setFactory(new ViewSwitcher.ViewFactory() {

			@Override
			public View makeView() {
				final TextView textView = new TextView(getActivity());
				textView.setText("超惟科技Lims系统");
				textView.setSingleLine();
				textView.setTextSize(15);
				textView.setTextColor(Color.parseColor("#ff333333"));
				FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.MATCH_PARENT);
				lp.gravity = Gravity.CENTER;
				textView.setLayoutParams(lp);
				textView.setSingleLine();
				textView.setEllipsize(TextUtils.TruncateAt.END);
				textView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Toast.makeText(getActivity(), textView.getText()
								.toString(), Toast.LENGTH_LONG);

					}
				});
				return textView;
			}
		});

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if (msgInfoList.size() > 0) {
					tsMsg.setText(msgInfoList.get(msgIndex));
					msgIndex++;
					if (msgIndex == msgInfoList.size()) {
						msgIndex = 0;
					}
				}
			}

		};

		myThread = new Thread() {
			@Override
			public void run() {
				while (msgIndex < msgInfoList.size() && isContinue) {
					mHandler.sendEmptyMessage(0);
					SystemClock.sleep(5000);
				}
			}
		};
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		isContinue = false;
		if (myThread != null && myThread.isAlive()) {
			myThread.interrupt();
		}
	}

	public void LoadMessage() {
		msgWrapper.Url = app.getUrl() + "/cwlims/informattorservice/ks2";
		msgWrapper.SoapAction = "http://soa.cwlims.business/IInformattorService/LoadByDays";
		msgWrapper.Namespace = "http://soa.cwlims.business";
		msgWrapper.MethodName = "LoadByDays";
		msgWrapper.MethodParameter = new LinkedHashMap<String, Object>();
		msgWrapper.MethodParameter.put("days", "-90");
		msgWrapper.MethodParameter.put("user", "003");
		msgWrapper.MethodParameter.put("post", "04");
		msgWrapper.MethodParameter.put("dept", "01");
		msgWrapper.MethodParameter.put("cert", cert);
		new SoapRequest(new AsyncMsgListener()).execute(msgWrapper);
	}

	public class AsyncMsgListener implements AsyncOptUIListener {

		private ArrayList<String> msgDateList = new ArrayList<String>();

		public void AsyncOpt(SoapObject soapObject) {
			if (soapObject != null && soapObject.getPropertyCount() > 0) {
				msgInfoList.clear();
				msgIndex = 0;
				SoapObject LoadByDaysResult = (SoapObject) soapObject
						.getProperty(0);
				for (int i = 0; i < LoadByDaysResult.getPropertyCount(); i++) {
					SoapObject msg = (SoapObject) LoadByDaysResult
							.getProperty(i);
					msgInfoList.add(msg.getPropertyAsString("_information"));
					msgDateList.add(msg.getPropertyAsString("_sentdate"));
				}
				if (!myThread.isAlive()) {
					myThread.start();
				}
			}
		}
	}

	/** 初始化数据 */
	private void initData() {
		insertTodo();
		insertNotappro();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("funcName", "更多");
		map.put("funcDraw", R.drawable.icon_home_grid_more);
		funcsList.add(map);
	}

	/** 为控件绑定数据源 */
	private void bindData() {
		// 适配器绑定数据
		entrAdapter = new SimpleAdapter(getActivity(), // 没什么解释
				funcsList, R.layout.item_entrance_gridview_home, new String[] {
						"funcDraw", "funcName" }, new int[] {
						R.id.iv_entra_img, R.id.tv_entra_text });
		todoAdapter = new SimpleAdapter(getActivity(), // 没什么解释
				todoList, R.layout.item_func_gridview_home, new String[] {
						"iv_item", "text_item" }, new int[] { R.id.iv_func_img,
						R.id.tv_func_text });
		notapproAdapter = new SimpleAdapter(getActivity(), // 没什么解释
				notapproList, R.layout.item_func_gridview_home, new String[] {
						"iv_item", "text_item" }, new int[] { R.id.iv_func_img,
						R.id.tv_func_text });
		// 添加adapter并且显示
		gvEntrance.setAdapter(entrAdapter);
		gvTodo.setAdapter(todoAdapter);
		gvNotapproved.setAdapter(notapproAdapter);

	}

	/** 为控件设置监听器 */
	private void setListener() {
		// 页面刷新监听
		mPullRefreshScrollView
				.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

					@Override
					public void onRefresh(
							PullToRefreshBase<ScrollView> refreshView) {
						String label = "更新于 "
								+ DateUtils.formatDateTime(getActivity()
										.getApplicationContext(), System
										.currentTimeMillis(),
										DateUtils.FORMAT_SHOW_TIME
												| DateUtils.FORMAT_SHOW_DATE
												| DateUtils.FORMAT_ABBREV_ALL);

						// 更新显示的label
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						new SoapRequest(new AsyncMsgListener())
								.execute(msgWrapper);
						new SoapRequest(new AsyncRefreshLoadTotalBillListener())
								.execute(totalBillWrapper);
						new SoapRequest(new AsyncLoadDetectionBillListener())
								.execute(detectionBillWrapper);
						new SoapRequest(new AsyncLoadNotApprovedBillListener())
								.execute(notApprovedBillWrapper);
					}
				});

		// 顶部搜索框监听
		etSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popSearch.showAtLocation((View) v.getParent(), Gravity.CENTER
						| Gravity.CENTER_HORIZONTAL, 0, 0);

			}
		});
		// 顶部头像点击监听
		linCircleHeader.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				MainActivity mian = (MainActivity) getActivity();
				LinearLayout lin_account = (LinearLayout) mian
						.findViewById(R.id.lin_bar_main_account);
				lin_account.performClick();

			}
		});
		// 顶部拍照监听
		imgPiture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent cameraIntent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent, PHOTO_REQUEST_TAKEPHOTO);
			}
		});
		// 搜索界面取消监听
		imgPopBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popSearch.dismiss();
			}
		});
		
		imgPopsearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				search();				
			}
		});

		edSearchPop.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					search();
				}
				return false;
			}
		});

		gvEntrance.setOnItemClickListener(new ItemClickListener());
		gvTodo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0:
					Toast.makeText(getActivity(), "等待开发中", Toast.LENGTH_SHORT).show();

					break;
				case 1:
					Toast.makeText(getActivity(), "等待开发中", Toast.LENGTH_SHORT).show();
					break;
				case 2:
					Toast.makeText(getActivity(), "等待开发中", Toast.LENGTH_SHORT).show();
					break;
				}

			}
		});
//		listSearchBill.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				HashMap<String, Object> map = (HashMap<String, Object>) listSearchBill
//						.getItemAtPosition(position);
//				toBillDetail(map);
//
//			}
//		});

	}

	private void toBillDetail(HashMap<String, Object> map) {
		Bundle bundle = new Bundle();
		bundle.putString("billstate", map.get("billstate").toString());
		bundle.putString("billcode", map.get("billcode").toString());
		bundle.putString("billitem", map.get("itemname").toString());
		bundle.putString("custname", map.get("custname").toString());
		bundle.putString("description", map.get("description").toString());
		bundle.putString("reportcode", map.get("reportcode").toString());
		bundle.putString("sampling", map.get("sampling").toString());
		bundle.putString("makedate", map.get("makedate").toString());
		bundle.putString("actualqty", map.get("actualqty").toString());
		bundle.putString("syscode", map.get("syscode").toString());
		Intent intent = new Intent(getActivity(), BillDetailActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	/** 加载所有委托单 */
	public void LoadTotalContracts() {

		totalBillWrapper.Url = app.getUrl()
				+ "/cwlims/internetaccountservice/ks2";
		totalBillWrapper.Namespace = "http://soa.cwlims.business";
		totalBillWrapper.SoapAction = "http://soa.cwlims.business/IInternetAccountService/LoadTotalContracts";
		totalBillWrapper.MethodName = "LoadTotalContracts";
		totalBillWrapper.MethodParameter = new LinkedHashMap<String, Object>();
		totalBillWrapper.MethodParameter.put("login_id", login_id);
		totalBillWrapper.MethodParameter.put("cert", cert);
		new SoapRequest(new AsyncInitLoadTotalBillListener())
				.execute(totalBillWrapper);
	}

	/**
	 * 加载待评审委托单
	 */
	public void LoadNotApprovedContracts() {

		notApprovedBillWrapper.Url = app.getUrl()
				+ "/cwlims/internetaccountservice/ks2";
		notApprovedBillWrapper.Namespace = "http://soa.cwlims.business";
		notApprovedBillWrapper.SoapAction = "http://soa.cwlims.business/IInternetAccountService/LoadNotApprovedContracts";
		notApprovedBillWrapper.MethodName = "LoadNotApprovedContracts";
		notApprovedBillWrapper.MethodParameter = new LinkedHashMap<String, Object>();
		notApprovedBillWrapper.MethodParameter.put("login_id", login_id);
		notApprovedBillWrapper.MethodParameter.put("cert", cert);
		new SoapRequest(new AsyncLoadNotApprovedBillListener())
				.execute(notApprovedBillWrapper);
	}

	/***
	 * 加载检测中的委托单
	 */
	public void LoadDetectionOfContracts() {
		detectionBillWrapper.Url = app.getUrl()
				+ "/cwlims/internetaccountservice/ks2";
		detectionBillWrapper.Namespace = "http://soa.cwlims.business";
		detectionBillWrapper.SoapAction = "http://soa.cwlims.business/IInternetAccountService/LoadDetectionOfContracts";
		detectionBillWrapper.MethodName = "LoadDetectionOfContracts";
		detectionBillWrapper.MethodParameter = new LinkedHashMap<String, Object>();
		detectionBillWrapper.MethodParameter.put("login_id", login_id);
		detectionBillWrapper.MethodParameter.put("cert", cert);
		new SoapRequest(new AsyncLoadDetectionBillListener())
				.execute(detectionBillWrapper);
	}

	/**
	 * 刚打开界面获得显示数据
	 */
	public class AsyncInitLoadTotalBillListener implements AsyncOptUIListener {

		@Override
		public void AsyncOpt(SoapObject soapObject) {
			if (soapObject != null && soapObject.getPropertyCount() > 0) {
				getData(soapObject);
				if (getActivity() != null) {

					totalBillAdapter = new BillAdapter(getActivity(),
							billRecentList,
							R.layout.item_billmaster_listview_home,
							new String[] { "billcode", "custname", "makedate",
									"billstate", "itemname", "description",
									"reportcode", "actualqty", "sampling" },
							new int[] { R.id.tv_bill_code,
									R.id.tv_bill_custname, R.id.tv_bill_date,
									R.id.tv_bill_state, R.id.tv_bill_itemname,
									R.id.tv_bill_Description,
									R.id.tv_bill_reportCode,
									R.id.tv_bill_actualqty,
									R.id.tv_bill_sampling, });

					//listTotalBill.setAdapter(totalBillAdapter);
				}
			}
		}

	}

	/**
	 * 刷新界面获得显示数据
	 */
	public class AsyncRefreshLoadTotalBillListener implements
			AsyncOptUIListener {

		@Override
		public void AsyncOpt(SoapObject soapObject) {
			if (soapObject != null && soapObject.getPropertyCount() > 0) {
				getData(soapObject);
				if (totalBillAdapter == null) {
					new SoapRequest(new AsyncInitLoadTotalBillListener())
							.execute(totalBillAdapter);
				} else {
					totalBillAdapter.notifyDataSetChanged();
				}
			}
		}
	}

	/**
	 * 解析数据
	 */
	public void getData(SoapObject soapObject) {
		SoapObject results = (SoapObject) soapObject.getProperty(0);
		billMasterList.clear();
		billRecentList.clear();
		for (int i = 0; i < results.getPropertyCount(); i++) {
			SoapObject re = (SoapObject) results.getProperty(i);
			String billcode = re.getPropertyAsString("_billcode");
			String custname = re.getPropertyAsString("_custname");
			String makedate = re.getPropertyAsString("_makedate");
			String itemname = app.getFormatString(re
					.getPropertyAsString("_itemname"));
			String description = app.getFormatString(re
					.getPropertyAsString("_sample_descript"));
			String reportcode = app.getFormatString(re
					.getPropertyAsString("_reportcode"));
			String sampling = app.getFormatString(re
					.getPropertyAsString("_sampling_billcode"));
			String actualqty = app.getFormatString(re
					.getPropertyAsString("_actualqty"));
			String actualqtyUnit = app.getFormatString(re
					.getPropertyAsString("_actualqty_unit"));
			String state = re.getPropertyAsString("_billstate");
			String syscode = re.getPropertyAsString("_syscode");

			Date date = app.StrToDate(makedate);
			String strDate = app.getDateFormat(date);
			String billstate = InitData.BillState.getName(Integer
					.parseInt(state));
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("billcode", billcode);
			map.put("custname", custname);
			map.put("makedate", strDate);
			map.put("itemname", itemname);
			map.put("description", description);
			map.put("reportcode", reportcode);
			map.put("sampling", sampling);
			map.put("actualqty", actualqty + " " + actualqtyUnit);
			map.put("billstate", billstate);
			map.put("syscode", syscode);
			billMasterList.add(map);
		}
		myComparator compar = new myComparator();
		java.util.Collections.sort(billMasterList, compar);
		for (int i = 0; i < 5; i++) {
			billRecentList.add(billMasterList.get(i));
		}

	}

	public void search() {
		// 隐藏键盘
		((InputMethodManager) edSearchPop.getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
				edSearchPop.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
		billSearchList.clear();
		String searchText = edSearchPop.getText().toString();
		if (TextUtils.isEmpty(searchText)) {
			Toast.makeText(getActivity(), "搜索内容为空", Toast.LENGTH_SHORT).show();
			if (searchBillAdapter != null) {
				searchBillAdapter.notifyDataSetChanged();
			}
		} else {
			for (HashMap<String, Object> map : billMasterList) {
				String s = map.get("billcode").toString() + " "
						+ map.get("custname").toString() + " "
						+ map.get("itemname").toString() + " "
						+ map.get("makedate").toString() + " "
						+ map.get("description").toString() + " "
						+ map.get("reportcode").toString() + " "
						+ map.get("sampling").toString() + " "
						+ map.get("billstate").toString();
				if (s.contains(searchText)) {
					billSearchList.add(map);
				}
			}
			if (billSearchList.size() <= 0) {
				Toast.makeText(getActivity(), "没有查询到相关内容", Toast.LENGTH_SHORT)
						.show();
			}
			if (searchBillAdapter == null) {
				searchBillAdapter = new BillAdapter(getActivity(),
						billSearchList, R.layout.item_billmaster_listview_home,
						new String[] { "billcode", "custname", "makedate",
								"billstate", "itemname", "description",
								"reportcode", "sampling", "actualqty" },
						new int[] { R.id.tv_bill_code, R.id.tv_bill_custname,
								R.id.tv_bill_date, R.id.tv_bill_state,
								R.id.tv_bill_itemname,
								R.id.tv_bill_Description,
								R.id.tv_bill_reportCode, R.id.tv_bill_sampling,
								R.id.tv_bill_actualqty });
				listSearchBill.setAdapter(searchBillAdapter);
			} else {
				searchBillAdapter.notifyDataSetChanged();
			}
		}
	}

	/**
	 * 显示待评审的委托单数量
	 */
	public class AsyncLoadNotApprovedBillListener implements AsyncOptUIListener {

		@Override
		public void AsyncOpt(SoapObject soapObject) {
			if (soapObject != null && soapObject.getPropertyCount() > 0) {
				SoapObject results = (SoapObject) soapObject.getProperty(0);

				tvNotApprove.setText("" + results.getPropertyCount());

			} else {
				// Toast.makeText(getActivity(), R.string.get_failed,
				// Toast.LENGTH_SHORT).show();
			}
			mPullRefreshScrollView.onRefreshComplete();
		}
	}

	/**
	 * 显示正在检测中的委托单数量
	 */
	public class AsyncLoadDetectionBillListener implements AsyncOptUIListener {

		@Override
		public void AsyncOpt(SoapObject soapObject) {
			if (soapObject != null && soapObject.getPropertyCount() > 0) {
				SoapObject results = (SoapObject) soapObject.getProperty(0);
				tvDetec.setText("" + results.getPropertyCount());
			}
		}

	}

	/** 初始化搜索 */
	private void initSearchPopuWindow() {

		ColorDrawable cd = new ColorDrawable(0x000000);
		popSearch.setBackgroundDrawable(cd);
		popSearch.setOutsideTouchable(true);
		popSearch.setFocusable(true);
		popSearch.update();
		popSearch.setOnDismissListener(new OnDismissListener() {

			// 在dismiss中恢复透明度
			public void onDismiss() {
				WindowManager.LayoutParams lp = getActivity().getWindow()
						.getAttributes();
				lp.alpha = 1f;
				getActivity().getWindow().setAttributes(lp);
				billSearchList.clear();
				edSearchPop.setText(null);
			}
		});

	}

	private void insertTodo() {
		todoList.clear();
		HashMap<String, Object> map = new HashMap<String, Object>();
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		HashMap<String, Object> map2 = new HashMap<String, Object>();
		map.put("iv_item", R.drawable.icon_home_lab);
		map.put("text_item", "待评审记录");
		map1.put("iv_item", R.drawable.icon_home_cust);
		map1.put("text_item", "待复核记录");
		map2.put("iv_item", R.drawable.icon_home_report);
		map2.put("text_item", "记录审核通过");
		todoList.add(map);
		todoList.add(map1);
		todoList.add(map2);
	}
	private void insertNotappro() {
		notapproList.clear();
		HashMap<String, Object> map = new HashMap<String, Object>();
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		HashMap<String, Object> map2 = new HashMap<String, Object>();
		HashMap<String, Object> map3 = new HashMap<String, Object>();
		map.put("iv_item", R.drawable.icon_home_lab);
		map.put("text_item", "待评审记录");
		map1.put("iv_item", R.drawable.icon_home_cust);
		map1.put("text_item", "待复核记录");
		map2.put("iv_item", R.drawable.icon_home_report);
		map2.put("text_item", "待复核报告");
		map3.put("iv_item", R.drawable.icon_home_report);
		map3.put("text_item", "报告退回");
		notapproList.add(map);
		notapproList.add(map1);
		notapproList.add(map2);
		notapproList.add(map3);
	}
	
	

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_TAKEPHOTO
				&& resultCode == Activity.RESULT_OK) {
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			cciAccount.setImageBitmap(photo);
		}
	}
}
